'''
Created on 12/01/2013

@author: Jorge
'''
from Classifier import Classifier
from sklearn import svm
import sys
import numpy as np
np.set_printoptions(threshold=sys.maxint)
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report, f1_score,confusion_matrix
from TF_IDF import TF_IDF
from NormalizeData import NormalizeData
from feature_selection.BinormalSeparationWithRandRoubin import BinormalSeparationWithRandRoubin
from feature_selection.OptimalFeatureForClassifiers import FeaturesForSVMLinear

class SCIKYSVM(Classifier):
    '''
    classdocs
    '''
        
    def train(self, X, Y):
        print 'training...' 
        x = np.array(X)
        y = np.array(Y)
        self.model = self.get_optimal_model(x,y)
    
        
    def test(self, X, Y):
        
        print 'testing...'
        x = np.array(X)
        predictions  = self.model.predict(x)
        f1 = f1_score(Y, predictions)
        print ' f1: ',f1
        print ' confusion matrix \n' , confusion_matrix(Y, predictions)
        print classification_report(Y, predictions)
        return f1
        
        
    def get_optimal_model(self, X, Y):
        C = 2.0**np.array(range(-5,16,2))
        tuned_parameters = [{
                             'kernel': ['linear'],
                             'C': C,
                             },
                            ]
        clf = GridSearchCV(svm.SVC(C=1, probability=True), tuned_parameters, score_func=f1_score)
        clf.fit(X, Y, cv=5)
        print clf.best_estimator_
        print classification_report(Y, clf.predict(X))
        return clf.best_estimator_
        
    
    
if __name__ == '__main__':
    classifier = SCIKYSVM()
    #classifier.setFeatureSelector(BinormalSeparationWithRandRoubin(700))
    #classifier.setFeatureSelector(FeaturesForSVMLinear())
    classifier.add_transformation_to_data(TF_IDF()) 
    #classifier.add_transformation_to_data(NormalizeData())
    classifier.run_train_and_test()
    #classifier.run_train_and_validation()
    #classifier.optimal_num_feature("svm_linear_rest")
    